<? if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class ProfileModel extends CI_Model {

    public function getRecentPostsByUser($userId) {
        $this->load->model('PollsModel');

        $this->db->select("posts.*");
        $this->db->select("messages.content as message_content");
        $this->db->select("events.title as event_title");
        $this->db->select("polls.topic as poll_topic");
        $this->db->from("posts");
        $this->db->join("users", "users.id = posts.user_id", "left");
        $this->db->join("messages", "messages.id = posts.message_id", "left");
        $this->db->join("polls", "polls.id = posts.poll_id", "left");
        $this->db->join("events", "events.id = posts.event_id", "left");
        $this->db->where("user_id", $userId);
        $this->db->order_by("date_posted","DESC");
        $this->db->limit(10);

        $query = $this->db->get();

        $posts = $query->result();
        $posts = $this->PollsModel->addPollOptionsToPosts($posts);

        return $posts;
    }


    public function getEventsAttendingByUser($userId) {
        $this->db->select("*");
        $this->db->from("events");
        $this->db->join("event_participants", "events.id = event_participants.event_id", "left");
        $this->db->where("user_id", $userId);
        $this->db->order_by("date","DESC");
        $this->db->limit(10);

        $query = $this->db->get();

        $result = $query->result();

        return $result;
    }


    public function getProfileByUserId($userId) {
        $this->db->select("*");
        $this->db->from("user_profiles");
        $this->db->join("users", "users.id = user_profiles.user_id");
        $this->db->join("avatars", "avatars.user_id = users.id", "left");
        $this->db->join("images", "images.id = avatars.image_id", "left");
        $this->db->where("user_profiles.user_id", $userId);
        $this->db->order_by("images.date_uploaded","DESC");
        $this->db->limit(1);
		$result_set = $this->db->get();
        $result = $result_set->result();

        if (count($result) == 0) {
            return NULL;
        }
        
        return $result[0];
	}


    public function updateProfileByUserId($userId, $profile) {
        $this->db->where('user_id', $userId);
        $this->db->update('user_profiles', $profile);
    }

    public function updateUserDataByUserId($userId, $data) {
        $this->db->where('id', $userId);
        $this->db->update('users', $data);
    }
}